<?php

namespace app\controllers\h5\uni;

use app\controllers\h5\base\H5Controller;
use app\models\AwardResult;
use app\models\Brand;
use app\models\marketing\MarketingGroup;
use app\models\News;
use app\models\order\Order;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\product\ProductCategory;
use app\models\SetUserUp;
use app\models\SupplierAddress;
use app\models\system\SetAd;
use app\models\system\SetAdCategory;
use app\models\system\SetApp;
use app\models\system\SetFlow;
use app\models\system\SetHome;
use app\models\system\SetNav;
use app\models\system\SetSwiper;
use app\models\user\User;
use app\redis\Cache;

/**
 * Class HomeController
 * @package app\controllers\h5\uni
 */
class HomeController extends H5Controller
{
    /**
     * uni home page
     *
     * @return \yii\web\Response
     */
    public function actionIndex()
    {
        // $data = Cache::get(Cache::$PAGE_HOME);
        $data = null;
        if ($data == null) {
            $set = SetHome::getLastOne();
            $data = [
                'app_name' => $this->appName(),
                'category' => $this->getCategory(),
                'swiper' => $this->swiper(),
                'shop' => $this->shop(),
                'nav' => [
                    'data' => $this->nav(),
                    'total' => $set->nav_total
                ],
                // 'day' => $this->day($set->day),
                // 'group' => $this->group($set->group),
                // 'brand' => $this->brand($set->brand, $set->brand_total),
                'recommend' => $this->recommend($set->product),
                // 'group_quantity' => $this->getGroupQuantity(),

                // 最新广告
                'ad_nav' => $this->adNav(),
                'ad_nav_title' => $this->adNavTitle(),
                'product_list' => $this->productList(),

                // 抽奖
                // 'award' => $this->award(),

                // 新闻
                'news' => $this->_news(),
            ];

            // Cache::set(Cache::$PAGE_HOME, json_encode($data));
        } else {
            $data = json_decode($data, true);
        }

        return $this->successEncode($data);
    }

    private function _news()
    {
        return News::find()
            ->where(['status' => 1])
            ->orderBy(['id' => SORT_DESC])
            ->asArray()
            ->one();
    }

    // 首页抽奖 显示数量
    public function actionAwardCount()
    {
        $set = SetUserUp::getLastOne();


        $count = HomeController::awardOrderCount();
        $need = (int)$set->award_num;

        $num = $need - $count % $need;

        // var_dump($num);exit;

        return $this->success([
            'count' => $num
        ]);
    }

    // 计算有效的抽奖订单
    public static function awardOrderCount()
    {
        // $set = SetUserUp::getLastOne();
        //
        // $query = Order::find()
        //     ->where(['!=', 'status', Order::$statusMapping['DELETE']])
        //     ->andWhere(['!=', 'status', Order::$statusMapping['REFUND']])
        //     ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
        //     ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
        //     ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
        //     ->andWhere(['>=', 'total_pay', $set->award_amount]);

        // 也可以根据状态查询
        $query = Order::find()
            ->where(['award_status' => 1]);

        // 已经返过
        $last = AwardResult::find()
            ->orderBy(['id' => SORT_DESC])
            ->one();
        if ($last) {
            $query->andWhere(['>=', 'create_time', $last->update_time]);
        }

        // var_dump((int)$query->count());exit;

        return (int)$query->count();
    }

    // 首页最新导航
    private function adNav()
    {
        $list = SetAdCategory::find()
            ->where(['status' => 1])
            ->orderBy(['id' => SORT_ASC])
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            $item['list'] = SetAd::find()
                ->where(['status' => 1])
                ->andWhere(['category_id' => $item['id']])
                ->with(['image'])
                ->orderBy(['id' => SORT_ASC])
                ->asArray()
                ->all();
        }

        return $list;
    }

    // 后面2个导航标题
    private function adNavTitle()
    {
        $list = SetAdCategory::find()
            ->where(['status' => 0])
            ->orderBy(['id' => SORT_ASC])
            ->asArray()
            ->all();

        return $list;
    }

    // 首页最新产品列表
    private function productList()
    {
        // 对应不同区商品
        $set = SetFlow::getLastOne();
        // var_dump($set->recommend_num);exit;

        // 3 => 文娱
        // 1 => 爆品
        // 2 => 线下
        $ids1 = ProductAreaList::find()
            ->where(['area_id' => 3])
            ->select(['product_id'])
            ->column();
        $ids2 = ProductAreaList::find()
            ->where(['area_id' => 1])
            ->select(['product_id'])
            ->column();
        $ids3 = ProductAreaList::find()
            ->where(['area_id' => 2])
            ->select(['product_id'])
            ->column();

        $list = [
            '3' => Product::find()
                ->where(['status' => Product::$statusMapping['OK']])
                ->andWhere(['id' => $ids1])
                ->orderBy(['id' => SORT_DESC])
                ->limit($set->recommend_num)
                ->with(['mainImage'])
                ->asArray()
                ->all(),
            '1' => Product::find()
                ->where(['status' => Product::$statusMapping['OK']])
                ->andWhere(['id' => $ids2])
                ->orderBy(['id' => SORT_DESC])
                ->limit($set->recommend_num)
                ->with(['mainImage'])
                ->asArray()
                ->all(),
            '2' => Product::find()
                ->where(['status' => Product::$statusMapping['OK']])
                ->andWhere(['id' => $ids3])
                ->orderBy(['id' => SORT_DESC])
                ->limit($set->recommend_num)
                ->with(['mainImage'])
                ->asArray()
                ->all(),
        ];

        return $list;
    }

    private function getGroupQuantity()
    {
        $set = MarketingGroup::getLastOne();
        return $set->quantity;
    }

    private function appName()
    {
        $set = SetApp::getLastOne();

        return $set->app_name;
    }

    private function getCategory()
    {
        return ProductCategory::find()
            ->where(['status' => ProductCategory::$statusMapping['OK']])
            ->andWhere(['parent_id' => 0])
            ->select(['id', 'name'])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
            // 小程序首页限制数量
            // ->limit(4)
            ->asArray()
            ->all();
    }

    private function swiper()
    {
        return SetSwiper::find()
            ->where(['status' => SetSwiper::$statusMapping['OK']])
            // 首页的轮播图
            ->andWhere(['category_id' => 1])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['image'])
            // ->select(['id', 'image_id'])
            ->asArray()
            ->all();
    }

    // 商家轮播
    private function shop()
    {
        return SetSwiper::find()
            ->where(['status' => SetSwiper::$statusMapping['OK']])
            ->andWhere(['category_id' => 6])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['image'])
            // ->select(['id', 'image_id'])
            ->asArray()
            ->all();
    }

    private function nav()
    {
        $list = SetNav::find()
            ->where(['status' => SetNav::$statusMapping['OK']])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['image'])
            ->asArray()
            ->all();

        // var_dump($list);exit;

        return $list;
    }

    // 大礼包商品
    private function day($total)
    {
        $category_id = 181;

        return Product::find()
            ->where(['status' => Product::$statusMapping['OK']])
            ->andWhere(['category_id' => $category_id])
            ->orderBy(['id' => SORT_DESC])
            ->limit($total)
            ->with(['mainImage'])
            ->asArray()
            ->all();
    }

    private function group($total)
    {
        $ids = ProductAreaList::find()
            ->where(['area_id' => 5])
            ->limit($total)
            ->orderBy(['id' => SORT_DESC])
            ->select(['product_id'])
            ->column();

        return Product::find()
            ->where(['status' => Product::$statusMapping['OK']])
            ->andWhere(['id' => $ids])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['mainImage'])
            ->asArray()
            ->all();
    }

    private function brand($total, $product_total)
    {
        $list = Brand::find()
            ->where(['status' => Brand::$statusMapping['OK']])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->limit($total)
            ->with(['image', 'products', 'products.mainImage'])
            ->asArray()
            ->all();

        // 处理tag, products数量
        foreach ($list as &$item) {
            $tags = str_replace('，', ',', $item['tag']);
            $tags = explode(',', $tags);
            $item['tags'] = $tags;

            // 最多只取4个商品
            if (count($item['products']) > $product_total ) {
                $item['products'] = array_slice($item['products'], 0, $product_total);
            }
        }

        return $list;

        /**
         * todo
         * 必须取出有商品 > 3 的品牌,
         * 再根据后台设置的排序输出
         */
    }

    private function recommend($total)
    {
        return Product::find()
            ->where(['status' => Product::$statusMapping['OK']])
            // 这里需要推荐, 就让显示在首页
            ->andWhere(['is_recommend' => 1])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['mainImage'])
            ->limit($total)
            ->asArray()
            ->all();
    }

    // 首页显示数量
    public function actionNum()
    {
        $count = Order::find()
            ->where(['total_pay' => 22])
            ->count();

        $set = SetFlow::getLastOne();

        return $this->successEncode(['num' => $set->recommend_num + intval($count)]);
    }

    // 地区处理
    public function actionAddress()
    {
        // 如果登录了, 则改变地区
        // if ($this->user) {
        //     $address_id = User::find()
        //         ->where(['id' => $this->user->id])
        //         ->select(['address_id'])
        //         ->scalar();
        // } else {
        //     $address_id = 0;
        // }

        // 要从缓存中获取
        $address_id = $this->post('Address_id', 0);

        // var_dump($address_id);exit;

        if ($address_id) {
            $first = SupplierAddress::find()
                ->where(['status' => 1])
                ->andWhere(['id' => $address_id])
                ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
                ->asArray()
                ->all();

            $address = SupplierAddress::find()
                ->where(['status' => 1])
                ->andWhere(['!=', 'id', $address_id])
                ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
                ->asArray()
                ->all();

            $list = array_merge($first, $address);
        } else {
            $address = SupplierAddress::find()
                ->where(['status' => 1])
                ->orderBy(['sort' => SORT_ASC, 'id' => SORT_ASC])
                ->asArray()
                ->all();
            $list = $address;
        }

        // var_dump($list);exit;

        return $this->successEncode([
            'list' => $list,
        ]);
    }

    // 新加的首页分类商品
    public function actionHomeProduct()
    {
        $id = $this->post('id');

        $limit = SetFlow::getLastOne()->recommend_num;

        $list = Product::find()
            ->where(['status' => Product::$statusMapping['OK']])
            ->andWhere(['category_id' => $id])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->with(['mainImage'])
            ->limit($limit)
            ->asArray()
            ->all();

        return $this->successEncode(['list' => $list]);
    }
}